package com.xinke.component.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

/**
 * @Author yzx
 * @CreateTime 2025/3/23 16:18
 * @Version 1.0
 * @Description:    雪花算法ID生成器
 */
@Slf4j
public class SnowFlake {
    // 起始时间戳（2020-01-01 00:00:00）
    private final static long START_STAMP = 1577808000000L;

    // 各部分位数分配
    private final static long SEQUENCE_BIT = 12;   // 序列号位数
    private final static long MACHINE_BIT = 5;     // 机器标识位数
    private final static long DATACENTER_BIT = 5;  // 数据中心位数

    // 最大值计算
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
    private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);

    // 各部分左移量
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    @Value("${xinke.snowflake.datacenterId:0}")
    private static final long datacenterId=0;  // 数据中心ID
    @Value("${xinke.snowflake.machineId:0}")
    private static final long machineId = 0;     // 机器ID
    private long sequence = 0L;       // 序列号
    private long lastStamp = -1L;     // 上次时间戳

    // 保持原有实现，添加单例模式
    private static volatile SnowFlake instance;

    public static SnowFlake getInstance() {
        if (instance == null) {
            synchronized (SnowFlake.class) {
                if (instance == null) {
                    // 从配置获取参数（需要提前配置）
                    log.debug("SnowFlake init datacenterId:{}, machineId:{}", datacenterId, machineId);
                    instance = new SnowFlake(datacenterId, machineId);
                }
            }
        }
        return instance;
    }
    private SnowFlake(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID can't be greater than " + MAX_DATACENTER_NUM + " or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("Machine ID can't be greater than " + MAX_MACHINE_NUM + " or less than 0");
        }
    }
    /**
     * 生成下一个ID
     */
    public synchronized long nextId() {
        long currStamp = getNewStamp();
        if (currStamp < lastStamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }

        if (currStamp == lastStamp) {
            // 相同毫秒内序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 同一毫秒内序列号已达到最大
            if (sequence == 0L) {
                currStamp = getNextMill();
            }
        } else {
            // 新毫秒重置序列号
            sequence = 0L;
        }

        lastStamp = currStamp;

        return (currStamp - START_STAMP) << TIMESTAMP_LEFT
                | datacenterId << DATACENTER_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }
    private long getNextMill() {
        long mill = getNewStamp();
        while (mill <= lastStamp) {
            mill = getNewStamp();
        }
        return mill;
    }

    private long getNewStamp() {
        return System.currentTimeMillis();
    }
}
